﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjaxControlToolkit;
using IndyMosaic.Models.Web;
using System.Web.UI.WebControls;

namespace IndyMosaic.Org.Site.Views.Shared
{
    public partial class BinaryResourceControl : System.Web.Mvc.ViewUserControl<IndyMosaic.Models.Web.BinaryResource>
    {
        BinaryResourceRepository repository = new BinaryResourceRepository();
        protected void FileUpload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
        {
            AsyncFileUpload fileUpload = (AsyncFileUpload)sender;
            if (fileUpload.HasFile)
            {
                if (repository.ValidContentType(fileUpload.FileName))
                {
                    BinaryResource br = new BinaryResource();
                    br.Binary = fileUpload.FileBytes;
                    br.ContentType = repository.GetContentType(fileUpload.FileName);
                    br.FileName = fileUpload.FileName;
                    repository.Create(br);
                    repository.Save();

                    BinaryResourceEventArgs args = new BinaryResourceEventArgs(br.ID);
                    OnBinaryResourceUpload(args);
                }
            }
            else
            {
                Label errorLabel = (Label)this.Page.FindControl("ErrorLabel");
                errorLabel.Text = "Sorry, we don't support that kind of file.";
            }
        }

        protected void OnBinaryResourceUpload(BinaryResourceEventArgs e)
        {
            if (BinaryResourceUploaded != null)
            {
                BinaryResourceUploaded(this, e);
            }
        }
        public event BinaryResourceUploadEventHandler BinaryResourceUploaded;

        public delegate void BinaryResourceUploadEventHandler(object sender, BinaryResourceEventArgs e);
    }

    public class BinaryResourceEventArgs
    {
        public BinaryResourceEventArgs(Guid id)
        {
            ID = id;
        }
        public Guid ID { get; set; }
    }
}
